package router

import (
	"github.com/cuiyuanxin/airuisi-admin/internal/middleware"
	v1 "github.com/cuiyuanxin/airuisi-admin/internal/router/v1"
	"github.com/cuiyuanxin/airuisi-admin/pkg/config"
	"github.com/cuiyuanxin/airuisi-admin/pkg/limiter"
	"github.com/gin-gonic/gin"
	"github.com/opentracing/opentracing-go"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"go.uber.org/zap"
	"net/http"
	"time"
)

func NewRouter(configSetting *config.Configs, loger *zap.Logger, tracet opentracing.Tracer) *gin.Engine {
	r := gin.New()

	r.Use(middleware.AppInfoMiddleware(configSetting))

	// 链路追踪
	r.Use(middleware.TarcingMiddleware(tracet))

	if configSetting.Server.Mode == "debug" {
		r.Use(gin.Logger())
		r.Use(gin.Recovery())
	} else {
		gin.DisableConsoleColor()
		r.Use(middleware.AccessLogMiddleware(loger))
		r.Use(middleware.RecoveryMiddleware(loger))
	}
	//
	r.Use(middleware.CorsMiddleware())
	if configSetting.Server.Ssl {
		r.Use(middleware.TlsMiddleware(configSetting, loger))
	}

	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"say": "Hi airuisi admin!",
		})
	})
	// 测试通信
	r.GET("ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "pong",
		})
	})
	// 限流器
	var methodLimiters = limiter.NewMethodLimiter().AddBuckets(limiter.LimiterBucketRule{
		Key:          "/auth",
		FillInterval: time.Second,
		Capacity:     10,
		Quantum:      10,
	})

	r.Use(middleware.RateLimiterMiddleware(methodLimiters))
	r.Use(middleware.ContextTimeoutMiddleware(configSetting.App.DefaultContextTimeout * time.Second))

	//r.StaticFS("/static/qrcode", http.Dir(global.WxInfoSetting.QrcodeSavePath))
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	apiR := r.Group("/api")
	{
		v1.SetupRouter(apiR)
	}

	return r
}
